package com.example.back.controller;

import com.example.back.common.Result;
import com.example.back.entity.Company;
import com.example.back.entity.Store;
import com.example.back.service.CompanyService;
import com.example.back.service.StoreService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/Company")
public class CompanyController {
    @Resource
    private CompanyService companyService;
    @Resource
    private StoreService storeService;

    //查找公司所有信息
    @GetMapping("/find")
    public Result find() {
        return Result.success(companyService.list());
    }

    //删除
    @PostMapping("/delete")
    public Result delete(@RequestBody Company company) {
        try{
            List<Store> all = storeService.list();
            for (Store store : all){
                if (store.getStoreCompany().equals(company.getCompanyId())){
                    return Result.error("删除失败，请检查是否有该公司的仓库在录");
                }
            }
            if (companyService.getById(company.getCompanyId()) == null) {
                return Result.error("公司删除失败");
            } else {
                return Result.success(companyService.removeById(company.getCompanyId()),"公司删除成功");
            }
        }catch(Exception ex){
            return Result.error("公司删除失败ERROR");
        }

    }


    //根据ID查询
    @PostMapping("/get")
    public Result get(@RequestBody Company company) {
        try{
            List<Company> companyList = new ArrayList<>(5);

            if (companyService.getById(company.getCompanyId()) != null) {
                companyList.add(companyService.getById(company.getCompanyId()));
                return Result.success(companyList,"公司查找成功");
            }
            else {
                return Result.error("公司查找失败");
            }
        }catch(Exception ex){
            return Result.error("公司查找失败ERROR");
        }


    }

    //根据公司id修改公司信息
    @PostMapping("/modify")
    public Result modify (@RequestBody Company company){
        try{
            if (companyService.getById(company.getCompanyId()) == null || companyService.list().size() == 0||company.getCompanyId() == null) {
                return Result.error("修改失败");
            } else {
                return Result.success(companyService.updateById(company),"修改成功");
            }
        }catch(Exception ex){
            return Result.error("修改失败ERROR");
        }

    }

    //新增
    @PostMapping("/add")
    public Result add (@RequestBody Company company){
        try{
            if (companyService.getById(company.getCompanyId()) != null){
                return Result.error("添加失败，请检查公司是否已经存在");
            }
            else{
                return Result.success(companyService.save(company),"公司添加成功");
            }
        }catch(Exception ex){
             return Result.error("公司添加失败ERROR，违反主键约束，请输入其他ID");
        }
    }

}

